/*
 * jQuery File Upload Plugin JS Example 8.9.0
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, regexp: true */
/*global $, window, blueimp */

$(function() {
    'use strict';

    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: 'server/php/'
    });

    // Enable iframe cross-domain access via redirect option:
    $('#fileupload').fileupload(
        'option',
        'redirect',
        window.location.href.replace(
            /\/[^\/]*$/,
            '/cors/result.html?%s'
        )
    );

    if (window.location.hostname === 'blueimp.github.io') {
        // Demo settings:
        $('#fileupload').fileupload('option', {
            url: '//jquery-file-upload.appspot.com/',
            // Enable image resizing, except for Android and Opera,
            // which actually support image resizing, but fail to
            // send Blob objects via XHR requests:
            disableImageResize: /Android(?!.*Chrome)|Opera/
                .test(window.navigator.userAgent),
            maxFileSize: 5000000,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
        });
        // Upload server status check for browsers with CORS support:
        if ($.support.cors) {
            $.ajax({
                url: '//jquery-file-upload.appspot.com/',
                type: 'HEAD'
            }).fail(function() {
                $('<div class="alert alert-danger"/>')
                    .text('Upload server currently unavailable - ' +
                        new Date())
                    .appendTo('#fileupload');
            });
        }
    } else {
        // Load existing files:
        $('#fileupload').addClass('fileupload-processing');
        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            url: $('#fileupload').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload')[0]
        }).always(function() {
            $(this).removeClass('fileupload-processing');
        }).done(function(result) {
            $(this).fileupload('option', 'done')
                .call(this, $.Event('done'), {
                    result: result
                });
        });
    }
});

var IG;
var AlbumList;
var param = {
    client_id: "da8ed14f202a4cc1ad434afa84fa985d",
    redirect_uri: "http://localhost/travelAlbum/",
    scope: "basic",
    response_type: 'token'
}
try {
    var token = $.jStorage.get("insta_access_token", null);
}
catch (e){

}

if (typeof IG == 'undefined') {
    IG = new Instagram();
}
if (token != null) {
    setInstaToken(token);
}
//Router
var AppRouter = Backbone.Router.extend({
    routes: {
        "": "defaultRoute",
        "mygallery": "myGallery",
        "createalbum": "createAlbum",
        "display": "display",
        "*actions": "access_token",
    }
});
var app_router = new AppRouter();

app_router.on('route:defaultRoute', function() {
    var el = document.getElementById("content-container");
    el.innerHTML = "";
    console.log("hi");

    var template = _.template($('#file-upload').html(), {});
    $('#content-container').html(template);
});


app_router.on('route:myGallery', function(actions) {
    console.log("Gallery");
    var el = document.getElementById("content-container");
    el.innerHTML = "";
    $.get('http://localhost/travelAlbum/server/php/albumInfo.txt', function(data) {
        AlbumList = readAlbum(data);
        var template = _.template($('#album-gallery').html(), {});
        $('#content-container').append(template);
        console.log(AlbumList);
        for (var i = 0; i < AlbumList.length; i++) {
            var src = getUrlFromName(AlbumList[i].photo[0]);
            console.log(src);
            var album = {
                id: i,
                src: src,
                name: AlbumList[i].name,
            }
            var template = _.template($('#image-list-item').html(), {
                album: album
            });
            $("#myGallery").append(template);
        }
        $(document).ready(function() {
            $('#myGallery').ImageOverlay();
        });
    });

});

app_router.on('route:createAlbum', function(actions) {
    var el = document.getElementById("content-container");
    el.innerHTML = "";
    console.log("Create Album");
    var template = _.template($('#album-name').html(), {});
    $('#content-container').html(template);
    console.log(fileList);
    for (var i = 0; i < fileList.length; i++) {
        var file = fileList[i];
        img = {
            src: file.thumbnailUrl,
            name: file.name,
            id: i,
        }
        var template = _.template($('#image-option').html(), {
            img: img
        });
        $("select").append(template);
    }
    $("select").imagepicker({});
    var button = document.getElementById("save-album-button");
    button.addEventListener("click", saveAlbum);
});

app_router.on('route:display', function(actions) {
    console.log(selectedIndex);
    var template = _.template($('#display-album').html(),{});
    $('#content-container').html(template);
    initGoogleMap();
    var indexes = selectedIndex;
});
app_router.on('route:access_token', function(actions) {
    if (typeof IG == 'undefined') {
        IG = new Instagram();
    }
    console.log("access token");
    var token = IG.getToken();
    $.jStorage.set("insta_access_token", token);
    setInstaToken(token);
    app_router.navigate("", {
        trigger: true,
        replace: true
    });
});

Backbone.history.start();

function getSelectValues(select) {
    var result = [];
    var options = select && select.options;
    var opt;

    for (var i = 0, iLen = options.length; i < iLen; i++) {
        opt = options[i];

        if (opt.selected) {
            result.push(opt.value || opt.text);
        }
    }
    return result;
}

function saveAlbumInfo(info) {
    console.log("album info");
    console.log(info);
    var data = new FormData();
    data.append("data", info);
    var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
    xhr.open('post', 'server/php/', true);
    xhr.send(data);
}

function saveAlbum() {
    var e = document.getElementById("image-picker");
    selectedIndex = getSelectValues(e);
    albumName = $('#album-name-input').val();
    var d = new Date();
    var album_info = {
        name: albumName,
        photo: [],
        created_at: d.toGMTString(),
    }
    for (var i = 0; i < selectedIndex.length; i++) {
        album_info.photo.push(fileList[selectedIndex[i]].name);
    }
    var content = JSON.stringify(album_info) + "\n";
    saveAlbumInfo(content);
    app_router.navigate("display", {
        trigger: true
    });
}

function readAlbum(data) {
    var albumList = [];
    var lines = data.split("\n");
    console.log(lines);
    for (var i = 0; i < lines.length; i++) {
        var line = lines[i];
        if (line.length > 0) {
            albumList.push(JSON.parse(lines[i]));
        }
    }
    return albumList;
}

function getUrlFromName(fileName) {
    for (var i = 0; i < fileList.length; i++) {
        if (fileList[i].name == fileName) {
            return fileList[i].thumbnailUrl;
        }
    }
    return null;
}

function initGoogleMap(){
    console.log("initilizegoogleMap");
    $.getScript('https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&'+'callback=initializeMap',function(){});
}
var map;
var initializeMap = function() {
    console.log("initilizeMap");
      var mapOptions = {
        zoom: 4,
        center: new google.maps.LatLng(-25.363882,131.044922),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      
      map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);


      var southWest = new google.maps.LatLng(0.203405,5.244141);
      var northEast = new google.maps.LatLng(0.363882,0.044922);
      var bounds = new google.maps.LatLngBounds(southWest,northEast);
      map.fitBounds(bounds);
      var lngSpan = northEast.lng() - southWest.lng();
      var latSpan = northEast.lat() - southWest.lat();
      handleImage();
    }

    function setInstaToken(token) {
        IG.setOptions({
            token: token,
        });
        function callback(result){
            $("#instaLogin").text(result.data.full_name);
        }
        IG.currentUser(callback);
    }